package com.jiukuaidao.zhulin.module.commodity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jiukuaidao.library.base.BaseActivity;
import com.jiukuaidao.library.widget.banner.ConvenientBanner;
import com.jiukuaidao.zhulin.R;
import com.jiukuaidao.zhulin.data.TaskProvider;
import com.jiukuaidao.zhulin.entity.ApiGoosDetailInfo;
import com.jiukuaidao.zhulin.entity.EventShoppingCartInfo;
import com.jiukuaidao.zhulin.module.CommContract;
import com.jiukuaidao.zhulin.module.CommPresenter;
import com.jiukuaidao.zhulin.module.commodity.contract.GoodsDetailContract;
import com.jiukuaidao.zhulin.module.commodity.presenter.GoodsDetailPresenter;
import com.jiukuaidao.zhulin.module.shoppingcart.ShoppingCartActivity;
import com.jiukuaidao.zhulin.module.user.LoginActivity;
import com.jiukuaidao.zhulin.util.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Author : BinarySatan
 * Date : 2016/6/7
 * Description : 商品详情
 */
public class GoodsDetailActivity extends BaseActivity<GoodsDetailContract.Presenter> implements GoodsDetailContract.View, CommContract.ShoppingCartLocalView,View.OnClickListener {

    @BindView(R.id.banner)
    ConvenientBanner mBanner;
    @BindView(R.id.tv_goods_name)
    TextView mTvGoodsName;
    @BindView(R.id.tv_goods_promo)
    TextView mTvGoodsPromo;
    @BindView(R.id.tv_goods_price)
    TextView mTvGoodsPrice;
    @BindView(R.id.btn_add_shopcart)
    Button mBtnAddShopcart;
    @BindView(R.id.tv_goods_count)
    TextView mTvGoodsCount;
    @BindView(R.id.rl_add_reduce_shopcart)
    RelativeLayout mRLAddReduceShopcart;
    @BindView(R.id.tv_goods_evaluation)
    TextView mTvGoodsEvaluation;
    @BindView(R.id.iv_evaluation_arrow)
    ImageView mIvEvaluationArrow;
    @BindView(R.id.tv_goods_score)
    TextView mTvGoodsScore;
    @BindView(R.id.rbar)
    RatingBar mRbar;
    @BindView(R.id.tv_comment)
    TextView mTvComment;
    @BindView(R.id.tv_look_all_commment)
    TextView mTvLookAllCommment;
    @BindView(R.id.rl_goods_evaluation)
    RelativeLayout rlGoodsEvaluation;
    @BindView(R.id.iv_goods_reduce)
    ImageView mIvGoodsReduce;
    @BindView(R.id.iv_goods_add)
    ImageView mIvGoodsAdd;

    @BindView(R.id.goods_params)
    TextView goodsParams;
    @BindView(R.id.ll_goods_attribute)
    LinearLayout mLLGoodsAttribute;

    @BindView(R.id.goods_described)
    TextView mGoodsDescribed;  //文描
    @BindView(R.id.tv_goods_described)
    TextView mTvGoodsDescribed; //文描内容

    @BindView(R.id.iv_left_back)
    ImageView mLeftBack; //左侧返回按钮
    // 配送费
    @BindView(R.id.fab_shopingcart)
    TextView fabShopingcart;
    // 购物车商品数量
    @BindView(R.id.tv_cartnum)
    TextView tvCartnum;
    // 购物车整体布局
    @BindView(R.id.rl_shopingcart)
    RelativeLayout rlShopingcart;

    private String mGoodsId; //商品id
    private String mGoodsNumber; //商品number
    private int mGoodsCount; //商品个数
    private String mGoodsPrice; //商品价格
    private String mStartPrice; //起送价
    private String mFullShipmentFree; //满多少免配送费
    private List<EventShoppingCartInfo> mShoppingCartDataLocal;

    private CommPresenter mCommPresenter;

    @Override
    protected View getTargetView() {
        return null;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_commodity_goods_detail;
    }

    @Override
    protected void handleBundle(Bundle bundle) {
        mGoodsId = bundle.getString("goodsId");
        mStartPrice = bundle.getString("startPrice"); //起送价
        mFullShipmentFree = bundle.getString("fullShipmentFree");
    }

    @Override
    protected void init() {

        EventBus.getDefault().register(this);
        new GoodsDetailPresenter(TaskProvider.provideTasksRepository(this), this);

        mCommPresenter = new CommPresenter(TaskProvider.provideTasksRepository(this), this);
        mPresenter.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mBanner.stopTurning();
    }

    @Override
    public String getGoodsId() {
        return mGoodsId;
    }


    @Override
    public List<EventShoppingCartInfo> getShoppingCartDataLocal() {
        return mShoppingCartDataLocal;
    }

    @Override
    public void getGoodsDetailDataSuc(ApiGoosDetailInfo result) {

        mGoodsId = result.goods.id;//店铺id
        mGoodsNumber = result.goods.number;
        mGoodsPrice = result.goods.retailPrice;

        setBanner(result.goods.uri);

        // 配送费
        fabShopingcart.setText("￥" + mStartPrice + "元起送");

        mTvGoodsName.setText(result.goods.name);

        mTvGoodsPrice.setText(String.format(getString(R.string.rmb_symbol), result.goods.retailPrice));

        mTvGoodsDescribed.setText(result.goods.desc);

        if (TextUtils.isEmpty(result.goods.subtitle))  //促销语是否为空
            mTvGoodsPromo.setVisibility(View.GONE);
        else
            mTvGoodsPromo.setText(result.goods.subtitle);

        if (TextUtils.isEmpty(result.goods.desc)) { // 文描是否为空
            mGoodsDescribed.setVisibility(View.GONE);
            mTvGoodsDescribed.setVisibility(View.GONE);
        } else
            mTvGoodsDescribed.setText(result.goods.desc);

        if (result.comments != null) {
            ApiGoosDetailInfo.CommentsBean commentsBean = result.comments;
            if (commentsBean != null) {
                if (commentsBean.comment != null) {
                    mRbar.setRating(TextUtils.isEmpty(commentsBean.comment.userGrade) ? 0 : Float.valueOf(commentsBean.comment.userGrade));//星星等级
                    mTvComment.setText(TextUtils.isEmpty(commentsBean.comment.userComment) ? "暂无评论" : commentsBean.comment.userComment); //评论
                } else {
                    mRbar.setVisibility(View.GONE);
                    mTvComment.setVisibility(View.GONE);
                }
                mTvGoodsEvaluation.setText(String.format(getString(R.string.goods_evaluation), commentsBean.count)); //商品评价
                mTvGoodsScore.setText(String.format(getString(R.string.goods_score), commentsBean.avgGrade == null ? "0" : commentsBean.avgGrade)); //商品总评分
            } else {
                mRbar.setVisibility(View.GONE);
                mTvComment.setVisibility(View.GONE);
                mTvGoodsEvaluation.setVisibility(View.GONE);
                mTvGoodsScore.setVisibility(View.GONE);
            }

        } else {
            mRbar.setVisibility(View.GONE);
            mTvComment.setVisibility(View.GONE);
            mTvGoodsEvaluation.setVisibility(View.GONE);
            mTvGoodsScore.setVisibility(View.GONE);
        }


        dynamicAddGoodsAttribute(result.goods.attributes); //动态商品属性

        mCommPresenter.getShoppingCartDataLocal(); //加载购物车数据
    }


    /**
     * 动态添加商品属性
     */
    private void dynamicAddGoodsAttribute(List<ApiGoosDetailInfo.GoodsBean.AttributesBean> attributes) {

        for (int i = 0; i < attributes.size(); i++) {
            ApiGoosDetailInfo.GoodsBean.AttributesBean attribute = attributes.get(i);
            View view = LayoutInflater.from(this).inflate(R.layout.dynamic_goods_detail_attribute, new FrameLayout(this), false);

            TextView name = (TextView) view.findViewById(R.id.name);
            TextView value = (TextView) view.findViewById(R.id.value);
            name.setText(String.format(getString(R.string.goods_praams_info), attribute.name));
            value.setText(attribute.value);

            mLLGoodsAttribute.addView(view);
        }
    }

    /**
     * 添加购物车
     */
    @OnClick(R.id.btn_add_shopcart)
    public void clickAddShoppingCart() {
        mCommPresenter.addShoppingCartLocal();
    }

    /**
     * 添加购物车
     */
    @OnClick(R.id.iv_goods_add)
    public void clickAddShoppingCart(View v) {
        clickAddShoppingCart();
    }

    /**
     * 减购物车
     */
    @OnClick(R.id.iv_goods_reduce)
    public void clickReduceShoppingCart() {
        mCommPresenter.reduceShoppingCartLocal();
    }

    /**
     * 跳转购物车
     */
    @OnClick(R.id.rl_shopingcart)
    public void clickShoppingCart() {

        Bundle bundle = new Bundle();
        bundle.putString("startPrice", mStartPrice);
        bundle.putString("fullShipmentFree",mFullShipmentFree);
        startLoginJump(UserInfoUtil.isLogin(), ShoppingCartActivity.class, this.getClass(), LoginActivity.class, bundle);
    }

    @OnClick(R.id.iv_left_back)
    public void clickBack() {
        this.finish();
    }

    /**
     * 设置轮播图
     *
     * @param uri
     */
    private void setBanner(List<String> uri) {
        mBanner.setCanLoop(uri.size() > 1)
                .setPages(uri, R.mipmap.ic_launcher)
                .setPageIndicator(new int[]{R.mipmap.page_indicator_white, R.mipmap.page_indicator_focused_red})
                .startTurning(5000);
    }


    /**
     * 获取本地购物车数据成功
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventShoppingCartDataLocal(List<EventShoppingCartInfo> shoppingCartDatas) {
        mShoppingCartDataLocal = shoppingCartDatas;

        // 商品数量
        tvCartnum.setText(String.valueOf(mCommPresenter.getGoodsCountTotal()));

        String goodsCount = mPresenter.findGoods();

        if (goodsCount.equals("0")) {//如果购物车内有这个商品
            mBtnAddShopcart.setVisibility(View.VISIBLE);
            mRLAddReduceShopcart.setVisibility(View.GONE);
            mTvGoodsCount.setText(String.valueOf(goodsCount));
            return;
        }

        mBtnAddShopcart.setVisibility(View.GONE);
        mRLAddReduceShopcart.setVisibility(View.VISIBLE);
        mTvGoodsCount.setText(String.valueOf(goodsCount));
    }

    @Override
    public String getGoodsNumber() {
        return mGoodsNumber;
    }

    @Override
    public String getGoodsCurPrice() {
        return mGoodsPrice;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @OnClick({R.id.rl_goods_evaluation})
    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.rl_goods_evaluation:
                //跳转到评价列表页面
                Bundle bundle = new Bundle();
                bundle.putString("goodsId",getGoodsId());
                intentJump(GoodsCommentsActivity.class,bundle);
                break;
        }
    }
}
